package thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: 成金乘
 * @date: 2023/1/22 15:19
 * @description:
 */
//编写代码, 基于 Callable 实现 1+2+3+...+1000
    //Callable类似Runnable但是拥有返回值
public class ThreadDemo14 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int count = 0;
                for (int i = 0;i < 1000;i++){
                    count += i;
                }
                return count;
            }
        };
        FutureTask<Integer> future = new FutureTask<>(callable);
        Thread t = new Thread(future);//不能直接将Callable放入线程里,要套一层其他辅助类
        t.start();

        Integer result = future.get();
        System.out.println(result);
    }
}
//编写代码, 基于 AtomicInteger 实现多线程自增同一个变量
class Thread66{
    private static AtomicInteger atomicInteger = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
           for (int i = 0;i < 500;i++){
               atomicInteger.getAndIncrement();//原子类要通过此方法实现自增操作
           }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0;i < 500;i++){
                atomicInteger.getAndIncrement();//原子类要通过此方法实现自增操作
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("atomicInteger = "+atomicInteger);
    }
}
